
Component({
  properties: {
    // 默认选中的地区编码数组
    defaultIndexes: {
      type: Array,
      value: [0, 0, 0]
    }
  },

  data: {
    columns: [
      { values: [], className: 'column1' },
      { values: [], className: 'column2' },
      { values: [], className: 'column3' }
    ],
    areaData: [],
    selectedValues: []
  },

  lifetimes: {
    attached() {
      this.initPicker();
      this.loadAreaData();
    }
  },

  observers: {
    'defaultIndexes': function(indexes) {
      if (indexes && indexes.length > 0) {
        this.setIndexes(indexes);
      }
    }
  },

  methods: {
    // 加载地区数据
    loadAreaData() {
      const that = this;
      // 这里可以从服务器获取数据，或者使用本地json文件
      wx.request({
        url: 'https://your-api-domain.com/api/areas', // 替换为实际API地址
        method: 'GET',
        success(res) {
          if (res.data && res.data.code === 0) {
            that.setData({
              areaData: res.data.data
            });
            that.initProvinceData();
          }
        },
        fail() {
          // 如果API调用失败，使用默认数据
          that.loadDefaultData();
        }
      });
    },

    // 加载默认数据
    loadDefaultData() {
      // 这里可以放置默认的省市区数据
      const defaultData = [
        {
          code: '110000',
          name: '北京市',
          children: [
            {
              code: '110100',
              name: '北京市',
              children: [
                { code: '110101', name: '东城区' },
                { code: '110102', name: '西城区' }
              ]
            }
          ]
        }
        // 可以继续添加更多省份数据
      ];
      this.setData({ areaData: defaultData });
      this.initProvinceData();
    },

    // 初始化省份数据
    initProvinceData() {
      const provinces = this.data.areaData.map(item => ({
        code: item.code,
        name: item.name
      }));
      
      this.setData({
        'columns[0].values': provinces
      });
      
      // 初始化第一个省份的城市数据
      if (provinces.length > 0) {
        this.updateCityData(0);
      }
    },

    // 更新城市数据
    updateCityData(provinceIndex) {
      const province = this.data.areaData[provinceIndex];
      const cities = province.children ? province.children.map(item => ({
        code: item.code,
        name: item.name
      })) : [];
      
      this.setData({
        'columns[1].values': cities
      });
      
      // 更新第一个城市的区县数据
      if (cities.length > 0) {
        this.updateDistrictData(provinceIndex, 0);
      } else {
        this.setData({
          'columns[2].values': []
        });
      }
    },

    // 更新区县数据
    updateDistrictData(provinceIndex, cityIndex) {
      const province = this.data.areaData[provinceIndex];
      if (province.children && province.children[cityIndex]) {
        const districts = province.children[cityIndex].children ? 
          province.children[cityIndex].children.map(item => ({
            code: item.code,
            name: item.name
          })) : [];
          
          this.setData({
            'columns[2].values': districts
          });
        } else {
          this.setData({
            'columns[2].values': []
          });
        }
    },

    // 选择器变化事件
    onChange(event) {
      const { value, index, column } = event.detail;
      const { picker } = event.detail;
      
      // 第一列变化（省份）
      if (column === 0) {
        this.updateCityData(index);
        // 重置第二列为第一个城市
        picker.setColumnValues(1, this.data.columns[1].values);
        if (this.data.columns[1].values.length > 0) {
          this.updateDistrictData(index, 0);
          picker.setColumnValues(2, this.data.columns[2].values);
        }
      }
      // 第二列变化（城市）
      else if (column === 1) {
        const provinceIndex = this.getCurrentProvinceIndex(picker);
        this.updateDistrictData(provinceIndex, index);
        picker.setColumnValues(2, this.data.columns[2].values);
      }
    },

    // 获取当前省份索引
    getCurrentProvinceIndex(picker) {
      const provinceValues = picker.getColumnValues(0);
      const currentProvince = picker.getColumnValue(0);
      return provinceValues.findIndex(item => item.code === currentProvince.code);
    },

    // 确认选择
    onConfirm(event) {
      const values = event.detail;
      const selectedArea = {
        province: values[0],
        city: values[1],
        district: values[2]
      };
      
      this.triggerEvent('confirm', selectedArea);
      this.triggerEvent('close');
    },

    // 取消选择
    onCancel() {
      this.triggerEvent('close');
    },

    // 关闭弹窗
    onClose() {
      this.triggerEvent('close');
    },

    // 初始化选择器
    initPicker() {
      if (this.data.defaultIndexes && this.data.defaultIndexes.length === 3) {
        this.setIndexes(this.data.defaultIndexes);
      }
    },

    // 设置默认选中项
    setIndexes(indexes) {
      const [provinceIndex, cityIndex, districtIndex] = indexes;
      
      if (this.data.areaData.length > 0 && provinceIndex < this.data.areaData.length) {
        this.updateCityData(provinceIndex);
        
        const province = this.data.areaData[provinceIndex];
        if (province.children && cityIndex < province.children.length) {
          this.updateDistrictData(provinceIndex, cityIndex);
        }
      }
    }
  }
})
